package com.gmrz.uap.util;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;

public class EmailUtils extends PropertiesKit {
    /**
     * 发送简单邮件
     *
     * @param toEmail 收件人
     * @param subject 标题
     * @param msg     发送内容
     */
    public void sendSimpleEmail(String toEmail, String subject, String msg) throws Exception {
        loadPropertyFile("application.properties");

        Email email = new SimpleEmail();
        email.setHostName(getProperty("email.hostName"));
        email.setSmtpPort(getPropertyToInt("email.smtpPort"));
        email.setAuthenticator(new DefaultAuthenticator(getProperty("email.username"), getProperty("email.password")));
        email.setSSLOnConnect(getPropertyToBoolean("email.ssl"));
        email.setFrom(getProperty("email.address"));
        email.setSubject(subject);
        email.setMsg(msg);
        email.addTo(toEmail);
        email.send();
    }

    /**
     * 发送HTMl邮件
     *
     * @param toEmail 收件人
     * @param subject 标题
     * @param htmlMsg HTML内容
     * @param textMsg 文本内容
     * @throws Exception
     */
    public void sendHtmlEmail(String toEmail, String subject, String htmlMsg, String textMsg) throws Exception {
        loadPropertyFile("application.properties");

        HtmlEmail email = new HtmlEmail();
        email.setHostName(getProperty("email.hostName"));
        email.setSmtpPort(getPropertyToInt("email.smtpPort"));
        email.setAuthenticator(new DefaultAuthenticator(getProperty("email.username"), getProperty("email.password")));
        email.setSSLOnConnect(getPropertyToBoolean("email.ssl"));
        email.setFrom(getProperty("email.address"));
        email.setSubject(subject);
        email.addTo(toEmail);

        // set the html message
        email.setHtmlMsg(htmlMsg);

        // set the alternative message
        email.setTextMsg(textMsg);

        // send the email
        email.send();
    }
}
